import {
  Body,
  Controller,
  FileTypeValidator,
  MaxFileSizeValidator,
  ParseFilePipe,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { RequireLogin, UserInfo } from '@/common/decorator/custom.decorator';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { MulterStorageService } from '@/module/file/upload/storage.service';
import { FileInterceptor } from '@nestjs/platform-express';

@ApiTags('文件系统')
@RequireLogin()
@Controller('upload')
export class UploadController {

  constructor(
    private readonly uploadService: UploadService,
    private readonly storageService: MulterStorageService,
  ) {
  }


  @ApiOperation({
    summary: '单文件上传',
    description: '小文件一次性上传',
  })
  @Post('single')
  @UseInterceptors(FileInterceptor('file', { storage: new MulterStorageService().getStorageEngine() }))
  async uploadSingle(@UploadedFile(new ParseFilePipe({
    validators: [
      new MaxFileSizeValidator({ maxSize: 1024 * 1024 * 10, message: '单个文件最大不能超过10MB' }),
      new FileTypeValidator({ fileType: 'image/*' }),
    ],
  })) file: Express.Multer.File, @UserInfo('username') createBy: string) {


    return await this.uploadService.saveFile(file, createBy);
  }


  @ApiOperation({
    summary: '分片上传',
  })
  @Post('chunk')
  @UseInterceptors(FileInterceptor('file', { storage: new MulterStorageService().getStorageEngine() }))
  async uploadChunk(@UploadedFile(new ParseFilePipe({
    validators: [
      new MaxFileSizeValidator({ maxSize: 1024 * 1024 * 10, message: '单个文件最大不能超过10MB' }),
    ],
  })) file: Express.Multer.File, @Body() chunkData: { fileId: string; chunkIndex: number }) {
    return await this.uploadService.saveChunk(file, chunkData.fileId, chunkData.chunkIndex);
  }


  @ApiOperation({
    summary: '分片合并',
  })
  @Post('merge')
  async mergeChunk(@Body() chunkData: { fileId: string; totalChunks: number }, @UserInfo('username') createBy: string) {
    return await this.uploadService.mergeChunks(chunkData.fileId, chunkData.totalChunks, createBy);
  }
}
